import { db, Sequelize } from '../../dao/config/index';
import { converPage } from '../../bean/page';
import { error } from '../../utils/logger';
import dayjs from 'dayjs';
const UserIntegral = require("../../dao/models/f_user_integral_relation")(db, Sequelize);
const Order = require("../../dao/models/f_order")(db, Sequelize);
const Product = require("../../dao/models/f_product")(db, Sequelize);
const UserProductRelation = require("../../dao/models/f_user_product_relation")(db, Sequelize);
const UserTeamRelation = require("../../dao/models/f_user_team_relation")(db, Sequelize);
const LeaderOrderRelation = require("../../dao/models/f_leader_order_relation")(db, Sequelize);
const UserVip = require("../../dao/models/f_user_vip")(db, Sequelize);
const OrderProductRelation = require("../../dao/models/f_order_product_relation")(db, Sequelize);

Order.belongsToMany(Product, {
    through: OrderProductRelation,
    as: "products",
    forignkey: "productId"
});

Product.belongsToMany(Order, {
    through: OrderProductRelation,
    as: "orders",
    forignkey: "orderId"
});
OrderProductRelation.belongsTo(Order, {
    as: "order",
    forignkey: "orderId",
})


/**
 * @name 创建订单
 * @description 
 * 默认创建的订单是未支付的 需要支付后才会修改支付状态
 * 创建后将当前用户插入会员表
 * @todo 自提需要返积分
 * @todo 将当前用户插入会员表需要放入支付后进行
 */
async function createOrder({ userId, recommenderId, shipmentId, isMention, productId, count, totalPrice }) {
    const orderProductRelation = {
        productId,
        count,
        order: {
            userId,
            shipmentId,
            createTime: new Date(),
            recommenderId,
            isMention,
            totalPrice,
        }
    };
    // 创建订单 并修改用户购买指定商品的数量
    const relationModel = await OrderProductRelation.create(orderProductRelation, {
        include: { model: Order, as: "order" }
    });
    await UserProductRelation.update({ count }, { where: { userId, productId } });

    /**将用户加入会员表 每次购买商品刷新用户的会员日期*/
    const product = await Product.findById(productId), currentDate = dayjs(), { signInTime } = product;
    const initUserVip = { userId, beginDate: currentDate.toDate(), endDate: currentDate.add(signInTime, "days") };
    await UserVip.upsert(initUserVip,{ where: { userId }})

    return relationModel.getOrder();

}


/**
 * @name 添加团长与订单关联
 * @description 
 * (团队积分)
 * 当推荐人成为团长时才会加入表中成为有效的推荐积分
 * @todo 更新用户的团队奖 将有效推荐订单记录算出来的总分加入到用户的团队奖字段上
 */
async function addLeaderOrderRelation({ leaderId, memberId, orderId, count }) {
    const leaderVipModel = await UserVip.find({ userId: leaderId });
    // 如果推荐人是普通会员则不将订单加入有效关联中
    if (!leaderVipModel || leaderVipModel.level < 1) return;
    const relation = {
        leaderId, memberId, orderId, count
    };
    // 创建关联
    LeaderOrderRelation.create(relation);
}

/**
 * @name 添加商品和用户的积分关联
 * @description
 * 判断有没有推荐人 如果有推荐人则需要 同时产生两条关系 
 * 一条自己和商品的关联 (购买积分) 
 * 一条推荐人和商品的关系 (推荐积分)
 */
async function addUserIntegral({ userId, recommenderId, productId, orderId, count }) {
    const productModel = await Product.findById(productId);
    if (productModel == null) return;
    const { signInTime, recommenderSignInTime } = productModel, currentDate = dayjs();
    // 计算出购买人的关联结束日期

    const purchaserDiffDate = currentDate.add(signInTime, "days").toDate();
    const userIntegral = {
        userId,
        productId,
        beginDate: currentDate,
        endDate: purchaserDiffDate,
        type: 0,//默认为用户购买返现
        purchaser: userId,
        orderId,
        count,
    };
    if (recommenderId) {
        // 计算出推荐人的关联结束日期
        const recommendDiffDate = currentDate.add(recommenderSignInTime, "days").toDate();
        UserIntegral.create({ ...userIntegral, endDate: recommendDiffDate, type: 1 });
    }
    UserIntegral.create(userIntegral);
}


/**
 * @name 添加用户团队关联关系
 * @description 
 * 添加购买人和推荐人的关联关系，并调整推荐人会员等级
 */
async function addUserTeamRelationShip({ userId, recommenderId }) {
    if (!recommenderId) return;
    const relationShip = {
        leaderId: recommenderId,
        memberId: userId,
    };
    // 创建购买人和推荐人的关联 如果已存在关联则不更新
    await UserTeamRelation.findOrCreate({ where: relationShip, default: { ...relationShip, createTime: dayjs().toDate() } });


    /**调整等级 */
    // 查询出团长所对应的所有团员
    const countOfRecommenderMembers = await UserTeamRelation.count({
        where: {
            leaderId: recommenderId
        }
    });
    // 更改推荐人状态
    if (countOfRecommenderMembers >= 10) {
        await UserVip.update({ level: 1 }, { where: { userId: recommenderId } });
        // 推荐人的被关联关系 从中查找出被推荐人的推荐人(ancestorId 祖级id)
        const recommenderTeam = await UserTeamRelation.find({ where: { memberId: recommenderId } }), ancestorId = recommenderTeam.leaderId;
        const ancestorVipModel = await UserVip.find({ userId: ancestorId });
        // 如果祖级已经是团长了 则更改为超级团长（超级团长可以享受团员的所有有效团队 leader_order表 奖励）
        if (ancestorVipModel.level = 1) {
            await UserVip.update({ level: 2 }, { where: { userId: recommenderId } });
        }

    }
}

export async function mock() {
    try {
        const mockData = { userId: 24, recommenderId: 20, shipmentId: 7, isMention: 1, productId: 8, count: 10, totalPrice: 100.0 };
        const order = await createOrder(mockData), { id: orderId } = order;
        console.log(orderId);

        mockData.orderId = orderId;
        await addUserIntegral(mockData);
        await addUserTeamRelationShip(mockData);
        await addLeaderOrderRelation(mockData);
    } catch (error) {
        console.error(error);
    }
}